package com.jay.compass;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jay.compass.app.StarApplication;
import com.jay.compass.base.MessageItem;
import com.jay.compass.base.RecentItem;
import com.jay.compass.ble.BluetoothLeService;
import com.jay.compass.dialog.LocationInfoDialog;
import com.jay.compass.dialog.RemoteIdDialog;
import com.jay.compass.dialog.SendMessageDialog;
import com.jay.compass.utils.BTimer;

import android.support.v4.app.FragmentManager;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({ "NewApi", "HandlerLeak" })
public class MainActivity extends ActionBarActivity implements
		FragmentCallbackListener {
	private Toast mToast;

	private TextView chatTextView;
	private TextView locateTextView;
	private TextView statusTextView;
	private TextView aboutTextView;

	private ImageView chatImageView;
	private ImageView locateImageView;
	private ImageView statusImageView;
	private ImageView aboutImageView;
	private LinearLayout[] mImageViews;
	private int mCurIndex = 0;
	private int mLastIndex = 0;
	private FragmentChat mChat;
	private FragmentStatus mStatus;
	private FragmentTool mTool;

	private SendMessageDialog mSendMessageDialog;
	private RemoteIdDialog mRemoteIdDialog;

	private final int CONTACT_PICKER_RESULT = 0x88;
	private ProgressDialog btConnectDialog;

	public static int mConnectType = LoginActivity.CONNECT_TYPE_NONE;
	public static int mConnectStatus = 0;
	private String mSendId;
	private String mSendMsg;
	private ProgressDialog sendingDialog;

	public static final int SEND_TYPE_ICJC = 1;
	public static final int SEND_TYPE_XTZJ = 2;
	public static final int SEND_TYPE_DWSQ = 3;
	public static final int SEND_TYPE_TXSQ = 4;
	public static final int SEND_TYPE_SMSG = 5;

	// +++++ble
	private BluetoothAdapter mBluetoothAdapter;
	private static final int REQUEST_ENABLE_BT = 1;
	// Stop scanning after 10 seconds.
	private static final long SCAN_PERIOD = 10000;
	// private boolean mBleConnected = false;
	// private boolean mBtConnected = false;
	public String bleName = null;
	public String bleAddress = null;
	public BluetoothLeService mBluetoothLeService;
	private Handler mBleHandler;
	public static final int BT_2_0 = 99;
	public static final int BT_4_0 = 100;

	private boolean mBleServiceBinded = false;
	// -----ble
	private boolean isDestyroied = false;
	private boolean mBroadcastRegistered = false;

	private boolean mLeaveMain = false;

	public static String PHONE_BEIDOU_ID = "306323";
	private Handler mSendHandler;
	private LocationInfoDialog mLocationInfoDialog;
	private boolean isInBack = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			int left = msg.what;
			System.out.println("left time = " + left + "s");
			if (mCurIndex == 0) {
				mChat.onSecondPast(left);
			} else if (mCurIndex == 1) {
				mTool.onSecondPast(left);
			}
			if (mSendMessageDialog.isShowing()) {
				mSendMessageDialog.onSecondPast(left);
			}

		};
	};

	// Code to manage Service lifecycle.
	private final ServiceConnection mBleServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName componentName,
				IBinder service) {
			mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
					.getService();
			StarApplication.getInstance().saveBleService(mBluetoothLeService);
			mBleServiceBinded = true;

			scanLeDevice(true);
			System.out.println("Ble service connect");
			if (!mBluetoothLeService.initialize()) {
				System.out.println("Unable to initialize Bluetooth");
				finish();
			}
			// Automatically connects to the device upon successful start-up
			// initialization.
			mBluetoothLeService.connect(bleAddress);
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			mBluetoothLeService = null;
			mBleServiceBinded = false;
		}
	};

	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			System.out
					.println("mBroadcastRegistered = " + mBroadcastRegistered);
			if (!mBroadcastRegistered) {
				return;
			}
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				System.out.println("gatt connected");
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
					.equals(action)) {
				showTip("断开连接");
				getActionBar().setTitle("未连接");
				mConnectStatus = 0;
				// finish();
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
					.equals(action)) {
			} else if (BluetoothLeService.ACTION_DEVICE_FIND.equals(action)) {
				if (btConnectDialog.isShowing()) {
					btConnectDialog.dismiss();
				}
				if (mConnectStatus == 0) {
					mConnectStatus = 1;
					getActionBar().setTitle("已连接");
					mBluetoothLeService.sendCommand(SEND_TYPE_ICJC, null, null,
							null);
					StarApplication.getInstance().getSpUtil()
							.setLoginType(LoginActivity.CONNECT_TYPE_BLUETOOTH);
				}
			} else if (BluetoothLeService.ACTION_GATT_TOAST.equals(action)) {
				// if (isInBack)
				// return;
				showTip(intent
						.getStringExtra(BluetoothLeService.BROADCAST_TO_TOAST));
			} else if (BluetoothLeService.ACTION_GATT_NEW_MESSAGE
					.equals(action)) {
				String id = intent
						.getStringExtra(BluetoothLeService.NEW_MESSAGE_ID);
				String msg = intent
						.getStringExtra(BluetoothLeService.NEW_MESSAGE_MESSAGE);
				String name = "";
				long time = System.currentTimeMillis();

				int headRes = R.drawable.head_bg;
				name = getContactNameFromPhoneBook(MainActivity.this, id);
				if (name.length() < 1) {
					String tempId = id.substring(0, 3) + " "
							+ id.substring(3, 7) + " " + id.substring(7, 11);
					name = getContactNameFromPhoneBook(MainActivity.this,
							tempId);
				}
				if (name.length() < 1) {
					name = id;
					headRes = R.drawable.head_phone;
				}

				if (isInBack) {
					StarApplication.getInstance().showNotification(name, msg);
				}

				int new_num = StarApplication.getInstance().getRecentDB()
						.getRecentNewNum(id);

				StarApplication.getInstance().getMediaPlayer().start();

				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						id, headRes, name, msg, new_num + 1, time, 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);

				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, name, time, msg,
						headRes, true, 1, 0, id);

				StarApplication.getInstance().getMessageDB()
						.saveMsg(id, msgItem);
				mChat.updateRecentList();
			} else if (BluetoothLeService.ACTION_GATT_SEND_SUCCESS
					.equals(action)) {
				if (sendingDialog == null)
					return;
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}
				long time = System.currentTimeMillis();
				String name = "";
				int headRes = StarApplication.getHeads()[Integer
						.valueOf(mSendId.substring(mSendId.length() - 1)) % 10];
				if (isMobileNum(mSendId)) {
					headRes = R.drawable.head_bg;
					name = getContactNameFromPhoneBook(MainActivity.this,
							mSendId);
					if (name.length() < 1) {
						String tempId = mSendId.substring(0, 3) + " "
								+ mSendId.substring(3, 7) + " "
								+ mSendId.substring(7, 11);
						name = getContactNameFromPhoneBook(MainActivity.this,
								tempId);
						if (name.length() < 1) {
							name = mSendId;
							headRes = R.drawable.head_phone;
						}
					}
				} else {
					if (name.length() < 1) {
						name = mSendId;
					}
				}

				int new_num = StarApplication.getInstance().getRecentDB()
						.getRecentNewNum(mSendId);

				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						mSendId, headRes, name, mSendMsg, new_num, time, 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);
				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, name, time, mSendMsg,
						headRes, false, 0, 0, mSendId);
				StarApplication.getInstance().getMessageDB()
						.saveMsg(mSendId, msgItem);
				mChat.updateRecentList();
			} else if (BluetoothLeService.ACTION_GATT_SEND_FAILED
					.equals(action)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}
				showTip("发送失败");
			} else if (BluetoothLeService.ACTION_GATT_LOCATE.equals(action)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}
				float lat = intent.getFloatExtra(BluetoothLeService.LOCATE_LAT,
						0.0f);
				float lng = intent.getFloatExtra(BluetoothLeService.LOCATE_LNG,
						0.0f);
				mLocationInfoDialog.setLocation(lat, lng);
				mLocationInfoDialog.show();

			} else if (BluetoothLeService.ACTION_GATT_LOCATE_SUCCESS
					.equals(action)) {
				// if (sendingDialog.isShowing()) {
				// sendingDialog.dismiss();
				// }

			} else if (BluetoothLeService.ACTION_GATT_LOCATE_FAILED
					.equals(action)) {
				// if (sendingDialog.isShowing()) {
				// sendingDialog.dismiss();
				// }
			}
		}
	};

	private void scanLeDevice(final boolean enable) {

		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mBleHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if (isDestyroied) {
						return;
					}

					if (btConnectDialog.isShowing()) {
						btConnectDialog.dismiss();
					}

					if (mConnectStatus == 0) {
						mBluetoothAdapter.stopLeScan(mLeScanCallback);
						showTip("BLE 扫描超时");
					}
				}
			}, SCAN_PERIOD);

			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	// Device scan callback.
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					final String deviceName = device.getName();
					if (deviceName != null && deviceName.length() > 0) {

						if (deviceName.startsWith("CPLB")) {
							if (mConnectStatus == 0) {
								showTip("找到北斗设备");
								bleName = deviceName;
								bleAddress = device.getAddress();
								if (mBluetoothLeService != null) {
									mBluetoothLeService.connect(bleAddress);
								}
							}
						}
					}
				}
			});
		}
	};

	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter
				.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BluetoothLeService.ACTION_DEVICE_FIND);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_TOAST);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_NEW_MESSAGE);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SEND_SUCCESS);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SEND_FAILED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_LOCATE);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_LOCATE_SUCCESS);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_LOCATE_FAILED);

		return intentFilter;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		getWindow().setFlags(
//				WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
//				WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		setContentView(R.layout.activity_main);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		mConnectType = getIntent().getIntExtra(
				LoginActivity.CONNECT_TYPE_STRING,
				LoginActivity.CONNECT_TYPE_NONE);

		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			this.getActionBar().setIcon(R.drawable.icon_bluetooth);
		} else if (mConnectType == LoginActivity.CONNECT_TYPE_NONE) {
			this.getActionBar().setIcon(R.drawable.icon_none);
		} else if (mConnectType == LoginActivity.CONNECT_TYPE_WIFI) {
			this.getActionBar().setIcon(R.drawable.icon_wifi);
		}

		getActionBar().setTitle("未连接");

		mChat = new FragmentChat();
		mStatus = new FragmentStatus();
		mTool = new FragmentTool();
		initRes();
		setDefaultContent();

		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
			mBluetoothAdapter = bluetoothManager.getAdapter();
			btConnectDialog = ProgressDialog.show(MainActivity.this, "请等待...",
					"连接中");
			btConnectDialog.show();

			useBtConnect();
		}

		if (mConnectType == LoginActivity.CONNECT_TYPE_WIFI) {
		}
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
			mBroadcastRegistered = true;
		}

		if (StarApplication.getInstance().getSpUtil().getRemoteId() > 100) {
			PHONE_BEIDOU_ID = ""
					+ StarApplication.getInstance().getSpUtil().getRemoteId();
		}

		mSendHandler = new Handler();
	}

	void useBtConnect() {
		if (!getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			showTip("不支持蓝牙4.0");
			// not support, that we can change connect mode to other mode
			mConnectStatus = 0;
			return;
		}
		// here connect to ble device
		Intent gattServiceIntentFilter = new Intent(this,
				BluetoothLeService.class);
		if (!mBleServiceBinded) {
			bindService(gattServiceIntentFilter, mBleServiceConnection,
					BIND_AUTO_CREATE);
		}
		mBleHandler = new Handler();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isInBack = false;
		System.out.println("+onResume+");
		StarApplication.getInstance().getNotificationManager().cancel(0x00);
		if (!mBroadcastRegistered) {
			if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
				registerReceiver(mGattUpdateReceiver,
						makeGattUpdateIntentFilter());
				mBroadcastRegistered = true;
			}
		}
		if (mConnectStatus == 0) {
			getActionBar().setTitle("未连接");
		}
		BTimer.getInstance().setHandler(mHandler);
		mLeaveMain = false;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isInBack = true;
		System.out.println("+onPause+");
		BTimer.getInstance().setHandler(null);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			unregisterReceiver(mGattUpdateReceiver);
		} else if (mConnectType == LoginActivity.CONNECT_TYPE_WIFI) {
		}
		mConnectStatus = 0;
		System.out.println("connect type = " + mConnectType);

		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			if (mBleServiceBinded) {
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
				mBluetoothLeService.disconnect();
				System.out.println("unbind ble service");
				unbindService(mBleServiceConnection);
				isDestyroied = true;
			}
		}
	}

	private void setDefaultContent() {
		FragmentManager fm = getSupportFragmentManager();
		fm.beginTransaction().replace(R.id.container, mChat).commit();
	}

	private void initRes() {
		chatTextView = (TextView) findViewById(R.id.chat_text);
		locateTextView = (TextView) findViewById(R.id.locate_text);
		statusTextView = (TextView) findViewById(R.id.status_text);
		aboutTextView = (TextView) findViewById(R.id.about_text);

		chatImageView = (ImageView) findViewById(R.id.chat_imageView);
		locateImageView = (ImageView) findViewById(R.id.locate_imageView);
		statusImageView = (ImageView) findViewById(R.id.status_imageView);
		aboutImageView = (ImageView) findViewById(R.id.about_imageView);

		mImageViews = new LinearLayout[4];
		mImageViews[0] = (LinearLayout) findViewById(R.id.chat_layout);
		mImageViews[1] = (LinearLayout) findViewById(R.id.locate_layout);
		mImageViews[2] = (LinearLayout) findViewById(R.id.status_layout);
		mImageViews[3] = (LinearLayout) findViewById(R.id.about_layout);

		for (int i = 0; i < 4; i++) {
			mImageViews[i].setEnabled(true);
			mImageViews[i].setOnClickListener(new NaviOnClickListener());
			mImageViews[i].setTag(i);
		}
		mImageViews[0].setEnabled(false);
		mImageViews[0].setOnClickListener(new NaviOnClickListener());
		mImageViews[0].setTag(0);
		chatImageView.setImageResource(R.drawable.icon_chat);
		locateImageView.setImageResource(R.drawable.icon_locate2);
		statusImageView.setImageResource(R.drawable.icon_status2);
		aboutImageView.setImageResource(R.drawable.icon_about2);

		chatTextView.setTextColor(0xff228B22);
		locateTextView.setTextColor(Color.GRAY);
		statusTextView.setTextColor(Color.GRAY);
		aboutTextView.setTextColor(Color.GRAY);

		mRemoteIdDialog = new RemoteIdDialog(MainActivity.this);
		mRemoteIdDialog.setOnCancelListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mRemoteIdDialog.dismiss();

				// long time = System.currentTimeMillis();
				// int new_num = StarApplication.getInstance().getRecentDB()
				// .getRecentNewNum("13746337685");
				//
				// RecentItem item = new
				// RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
				// "13746337685", R.drawable.head_bg, "123", "你好，我不是傻逼"
				// + time, new_num + 1, time, 0);
				// StarApplication.getInstance().getRecentDB().saveRecent(item);
				//
				// MessageItem msgItem = new MessageItem(
				// MessageItem.MESSAGE_TYPE_TEXT, "123", time, "你好，我不是傻逼"
				// + time, R.drawable.head_bg, true, 1, 0,
				// "13746337685");
				//
				// StarApplication.getInstance().getMessageDB()
				// .saveMsg("13746337685", msgItem);
				// mChat.updateRecentList();
			}
		});

		mRemoteIdDialog.setOnSendListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String id = mRemoteIdDialog.getRemoteId();
				if (id.length() != 6) {
					showTip("请输入正确的卡号");
					mRemoteIdDialog.dismiss();
				}
				StarApplication.getInstance().getSpUtil()
						.setRemoteId(Integer.valueOf(id));
				PHONE_BEIDOU_ID = id;
				mRemoteIdDialog.setCurrentId(id);
				mRemoteIdDialog.dismiss();
			}
		});

		mSendMessageDialog = new SendMessageDialog(MainActivity.this);
		mSendMessageDialog.setOnCancelListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mSendMessageDialog.dismiss();
			}
		});

		mSendMessageDialog.setOnSendListener(new View.OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				byte[] head = new byte[13];
				head[0] = 0x00;
				head[1] = (byte) 0xbe;
				// head[2] = 6;

				String number = mSendMessageDialog.getPhoneNumber();
				// get date
				Date date = new Date();
				int year = date.getYear() % 100;
				int month = date.getMonth() % 100 + 1;
				int day = date.getDate() % 100;

				int hour = date.getHours() % 100;
				int min = date.getMinutes() % 100;
				int sec = date.getSeconds() % 100;
				head[2] = (byte) (year / 10 * 16 + year % 10);
				head[3] = (byte) (month / 10 * 16 + month % 10);
				head[4] = (byte) (day / 10 * 16 + day % 10);
				head[5] = (byte) (hour / 10 * 16 + hour % 10);
				head[6] = (byte) (min / 10 * 16 + min % 10);
				head[7] = (byte) (sec / 10 * 16 + sec % 10);

				double num;
				if (number.length() == 11) {
					num = Double.valueOf(number);
				} else {
					showTip("手机号码错误");
					return;
				}

				head[8] = (byte) ((num / 256 / 256 / 256 / 256) % 256);
				head[9] = (byte) ((num / 256 / 256 / 256) % 256);
				head[10] = (byte) ((num / 256 / 256) % 256);
				head[11] = (byte) ((num / 256) % 256);
				head[12] = (byte) (num % 256);

				int content_len = mSendMessageDialog.getContent().length();
				if (content_len < 1) {
					showTip("输入信息为空");
					return;
				}
				byte[] content = null;
				try {
					content = mSendMessageDialog.getContent().getBytes(
							BluetoothLeService.encoding);
					for (int i = 0; i < content.length; i++) {
						System.out.print(String.format("%02x ", content[i]));
					}
					System.out.println();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				byte[] total = new byte[13 + content.length];
				int index = 0;
				for (int i = 0; i < 13; i++) {
					total[index++] = head[i];
				}
				for (int i = 0; i < content.length; i++) {
					total[index++] = content[i];
				}

				for (int i = 0; i < total.length; i++) {
					System.out.print(String.format("%02x ", total[i]));
				}
				System.out.println();

				mSendId = mSendMessageDialog.getPhoneNumber();
				mSendMsg = mSendMessageDialog.getContent();

				if (mConnectStatus == 0) {
					showTip("请先连接设备");
					return;
				}

				if (!(isIdValid(PHONE_BEIDOU_ID))) {
					showTip("输入的ID或者消息无效");
					return;
				}
				if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
					mBluetoothLeService.sendCommand(SEND_TYPE_SMSG,
							PHONE_BEIDOU_ID, null, total);
					sendingDialog = ProgressDialog.show(MainActivity.this,
							"发送中", "请稍后...");

					if (!sendingDialog.isShowing())
						sendingDialog.show();
					mSendHandler.postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							if (sendingDialog.isShowing()) {
								sendingDialog.dismiss();
								showTip("发送超时");
							}
						}
					}, 10000);
				}
				mSendMessageDialog.dismiss();
			}
		});

		mLocationInfoDialog = new LocationInfoDialog(MainActivity.this);
		mLocationInfoDialog.setMapOnClick(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(MainActivity.this,
						BaiduMapActivity.class);
				intent.putExtra("LAT", mLocationInfoDialog.getLat());
				intent.putExtra("LNG", mLocationInfoDialog.getLng());
				startActivity(intent);
			}
		});
	}

	public static String toHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;
	}

	public String getContactNameFromPhoneBook(Context context, String phoneNum) {
		String contactName = "";
		ContentResolver cr = context.getContentResolver();
		Cursor pCur = cr.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?",
				new String[] { phoneNum }, null);
		if (pCur.moveToFirst()) {
			contactName = pCur
					.getString(pCur
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			pCur.close();
		}
		return contactName;
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@SuppressWarnings("deprecation")
	public void onBackPressed() {
		// AlertDialog isExit = new AlertDialog.Builder(this).create();
		// isExit.setTitle("提示");
		// isExit.setMessage("确定退出？");
		// isExit.setButton("确定", exitListener);
		// isExit.setButton2("取消", exitListener);
		// isExit.show();
		moveTaskToBack(false);
	}

	DialogInterface.OnClickListener exitListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			if (which == AlertDialog.BUTTON_POSITIVE) {
				finish();
			} else if (which == AlertDialog.BUTTON_NEGATIVE) {
				;
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.chat_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_message:
			new AlertDialog.Builder(MainActivity.this)
					.setTitle(R.string.select_message_title)
					.setItems(R.array.select_number_type,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (which == 0) {
										mSendMessageDialog.show();
									} else if (which == 1) {
										Intent intent = new Intent(
												Intent.ACTION_PICK,
												ContactsContract.Contacts.CONTENT_URI);
										startActivityForResult(intent,
												CONTACT_PICKER_RESULT);
									}
								}
							}).show();
			break;

		case R.id.action_remote_id:
			mRemoteIdDialog.show();
			break;
		case R.id.action_logout:
			StarApplication.getInstance().getSpUtil().setLoginType(-1);
			Intent intent = new Intent(MainActivity.this, LoginActivity.class);
			startActivity(intent);
			finish();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	class NaviOnClickListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mCurIndex = (Integer) (v.getTag());
			mImageViews[mCurIndex].setEnabled(false);
			mImageViews[mLastIndex].setEnabled(true);
			mLastIndex = mCurIndex;
			if (mCurIndex == 0) {
				chatTextView.setTextColor(0xff228B22);
				locateTextView.setTextColor(Color.GRAY);
				statusTextView.setTextColor(Color.GRAY);
				aboutTextView.setTextColor(Color.GRAY);
				chatImageView.setImageResource(R.drawable.icon_chat);
				locateImageView.setImageResource(R.drawable.icon_locate2);
				statusImageView.setImageResource(R.drawable.icon_status2);
				aboutImageView.setImageResource(R.drawable.icon_about2);
				FragmentManager fm = getSupportFragmentManager();
				fm.beginTransaction().replace(R.id.container, mChat).commit();
			} else if (mCurIndex == 1) {
				chatTextView.setTextColor(Color.GRAY);
				locateTextView.setTextColor(0xff228B22);
				statusTextView.setTextColor(Color.GRAY);
				aboutTextView.setTextColor(Color.GRAY);
				chatImageView.setImageResource(R.drawable.icon_chat2);
				locateImageView.setImageResource(R.drawable.icon_locate);
				statusImageView.setImageResource(R.drawable.icon_status2);
				aboutImageView.setImageResource(R.drawable.icon_about2);
				FragmentManager fm = getSupportFragmentManager();
				fm.beginTransaction().replace(R.id.container, mTool).commit();
			} else if (mCurIndex == 2) {
				chatTextView.setTextColor(Color.GRAY);
				locateTextView.setTextColor(Color.GRAY);
				statusTextView.setTextColor(0xff228B22);
				aboutTextView.setTextColor(Color.GRAY);
				chatImageView.setImageResource(R.drawable.icon_chat2);
				locateImageView.setImageResource(R.drawable.icon_locate2);
				statusImageView.setImageResource(R.drawable.icon_status);
				aboutImageView.setImageResource(R.drawable.icon_about2);
				FragmentManager fm = getSupportFragmentManager();
				if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
					mStatus.setCardId("" + mBluetoothLeService.getUid());
				}
				mStatus.setConnectStatus(mConnectStatus);
				mStatus.setConnectType(mConnectType);
				fm.beginTransaction().replace(R.id.container, mStatus).commit();
			} else if (mCurIndex == 3) {
				chatTextView.setTextColor(Color.GRAY);
				locateTextView.setTextColor(Color.GRAY);
				statusTextView.setTextColor(Color.GRAY);
				aboutTextView.setTextColor(0xff228B22);
				chatImageView.setImageResource(R.drawable.icon_chat2);
				locateImageView.setImageResource(R.drawable.icon_locate2);
				statusImageView.setImageResource(R.drawable.icon_status2);
				aboutImageView.setImageResource(R.drawable.icon_about);
			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CONTACT_PICKER_RESULT:
			if (data == null)
				break;
			Uri contactData = data.getData();
			Cursor cursor = managedQuery(contactData, null, null, null, null);
			cursor.moveToFirst();
			Contact contact = getContactPhone(cursor);
			showTip(contact.name + ": " + contact.number);
			System.out.println(contact.name + ": " + contact.number);
			// process the phone number
			String number = contact.number.replaceAll(" ", "");

			if (number.startsWith("+86")) {
				if (number.length() == 14) {
					number = number.substring(3);
				}
			}

			if (!isMobileNum(number)) {
				showTip(" 不是有效的手机号码");
			}

			Intent intent = new Intent(MainActivity.this, ChatActivity.class);
			intent.putExtra(FragmentChat.USER_ID, number);
			intent.putExtra(FragmentChat.USER_NAME, contact.name);
			System.out.println("set leave to true");
			mLeaveMain = true;
			leaveMainCallback();
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	private Contact getContactPhone(Cursor cursor) {
		// TODO Auto-generated method stub
		int phoneColumn = cursor
				.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
		int phoneNum = cursor.getInt(phoneColumn);
		Contact contact = new Contact();
		if (phoneNum > 0) {
			int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
			String contactId = cursor.getString(idColumn);
			Cursor phone = getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					null,
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
							+ contactId, null, null);
			if (phone.moveToFirst()) {
				for (; !phone.isAfterLast(); phone.moveToNext()) {
					int index = phone
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
					int index2 = phone
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
					String number = phone.getString(index);
					String name = phone.getString(index2);
					contact.name = name;
					contact.number = number;
				}
				if (!phone.isClosed()) {
					phone.close();
				}
			}
		}
		return contact;
	}

	@Override
	public void sendToBeidou(String id, String content) {
		// TODO Auto-generated method stub
		mSendId = id;
		mSendMsg = content;

		if (!(isIdValid(id) && isMsgNull(content))) {
			showTip("输入的ID或者消息无效");
			return;
		}

		if (mConnectStatus == 0) {
			showTip("请先连接设备");
			return;
		}

		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			mBluetoothLeService.sendCommand(SEND_TYPE_TXSQ, id, content, null);
			sendingDialog = ProgressDialog.show(MainActivity.this, "发送中",
					"请稍后...");

			if (!sendingDialog.isShowing())
				sendingDialog.show();

			mSendHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (sendingDialog.isShowing()) {
						sendingDialog.dismiss();
						showTip("发送超时");
					}
				}
			}, 10000);
		}
	}

	public boolean isIdValid(String id) {
		boolean result = true;
		if (id.length() < 1 || (id.length() > 6))
			return false;
		int iid = Integer.valueOf(id);
		if (iid < 100 && (iid > 100000)) {
			result = false;
		}
		return result;
	}

	public boolean isMsgNull(String msg) {
		return (msg.length() < 1) ? false : true;
	}

	public class Contact {
		public String name;
		public String number;
	}

	@Override
	public void updateSignal() {
		// TODO Auto-generated method stub
		if (mConnectStatus == 0) {
			showTip("请先连接设备");
			return;
		}
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			mBluetoothLeService.sendCommand(SEND_TYPE_XTZJ, null, null, null);
		} else if (mConnectType == LoginActivity.CONNECT_TYPE_WIFI) {
		}
	}

	@Override
	public void leaveMainCallback() {
		// TODO Auto-generated method stub
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			unregisterReceiver(mGattUpdateReceiver);
			mBroadcastRegistered = false;
		} else if (mConnectType == LoginActivity.CONNECT_TYPE_WIFI) {
		}
	}

	public boolean isMobileNum(String mobiles) {
		if (mobiles.length() < 5)
			return false;
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	@Override
	public void doLocate() {
		// TODO Auto-generated method stub
		if (mConnectStatus == 0) {
			showTip("请先连接设备");
			return;
		}

		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			System.out.println("send dwsq cmd");
			mBluetoothLeService.sendCommand(SEND_TYPE_DWSQ, null, null, null);
			sendingDialog = ProgressDialog.show(MainActivity.this, "定位中",
					"请稍后...");

			if (!sendingDialog.isShowing())
				sendingDialog.show();

			mSendHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (sendingDialog.isShowing()) {
						sendingDialog.dismiss();
						showTip("定位超时");
					}
					mBluetoothLeService.isLocateOp = false;
				}
			}, 10000);
		} else if (mConnectType == LoginActivity.CONNECT_TYPE_WIFI) {
		}
	}

	private void showTip(final String str) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mToast.setText(str);
				mToast.show();
			}
		});
	}
}
